package com.education.platform.api.pay.alipay;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;

import com.alipay.api.request.*;
import com.alipay.api.response.AlipayTradeAppPayResponse;

import com.education.platform.api.vo.request.PayRecordUpdateVO;
import com.education.platform.common.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;


import javax.servlet.http.HttpServletRequest;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import static com.education.platform.api.pay.alipay.AlipayConfig.ALIPAY_PUBLIC_KEY;

/**
 * 支付宝支付服务
 */
@Service
public class AliPayServiceImpl implements AliPayService{


    Logger logger = LoggerFactory.getLogger(AliPayService.class);

    /**
     * 默认client
     * 获得初始化的AlipayClient
     */
    AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.SERVER_URL, AlipayConfig.APP_ID, AlipayConfig.PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.INPUT_CHARSET, ALIPAY_PUBLIC_KEY, AlipayConfig.SIGN_TYPE);

    /**
     * 创建支付请求
     * <p>
     * 关键入参：
     * 参数名称	参数说明
     * out_trade_no	商户订单号，需要保证不重复
     * subject	订单标题
     * seller_id	实际收款账号，一般填写商户PID即可
     * total_amount	订单金额
     *
     * @param
     * @throws Exception
     */
    @Override
    public String payRequest( PayRecordUpdateVO aliPayRequestVO)  {

        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。
        // 以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody("购买历史豆");
        model.setSubject("购买历史豆");
        model.setOutTradeNo(aliPayRequestVO.getOrderNo());
        model.setTimeoutExpress("90m");
        model.setTotalAmount(aliPayRequestVO.getTotalPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        request.setNotifyUrl(AlipayConfig.NOTIFY_URL);
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            //就是orderString 可以直接给客户端请求，无需再做处理。
            logger.info("调用支付宝参数："+response.getBody());
            return response.getBody();
        } catch (Exception e) {
            e.printStackTrace();
           throw new BusinessException("创建支付订单失败");
        }
    }




    /**
     * 获取支付宝返回的参数
     * 返回map
     *
     * @param request
     * @return
     */
    @Override
    public Map<String, String> getParamFormRequest(HttpServletRequest request) {

        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        return params;
    }

}
